package com.jiaai.web.pay;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jiaai.auth.model.AccessUser;
import com.jiaai.exception.ServerException;
import com.jiaai.filter.aop.TokenIntercept;
import com.jiaai.guard.IGuardApi;
import com.jiaai.pay.IPayAPI;
import com.jiaai.pay.entitiy.PayOrderSearch;
import com.jiaai.pay.entitiy.VPay;
import com.jiaai.pay.entitiy.VPayCallbackData;
import com.jiaai.util.RequestUtils;
import com.jiaai.util.RestResultGenerator;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * <p>
 *支付接口定义
 * </p>
 *
 * @author 佳爱网络科技
 * @version V1.0
 * @title DepositConteller
 * @since 2017/11/14
 */
@RequestMapping("/api/v1/pay")
@Controller
public class PayConteller {
    private  static  final Logger log= LoggerFactory.getLogger(PayConteller.class);
    @Reference
    private IPayAPI payAPI;
    @Reference
    private IGuardApi guardApi;

    /**
     * 创建支付订单
     * @param pay
     * @return
     * @throws ServerException
     */
    @GetMapping("/create")
    public ModelAndView createOrder(VPay pay)throws ServerException{
        ModelAndView view=new ModelAndView("pay/create");
        pay=payAPI.createPayOrder(pay);
        PayRequestData requestDatal=new PayRequestData();
        requestDatal.setAmount(pay.getPrice().intValue()*100);
        requestDatal.setBusiness_no(pay.getOutTradeNo());
        requestDatal.setPage_url(requestDatal.getPage_url()+"?gold="+pay.getGold());
        requestDatal.setMobile(pay.getMobile());
        requestDatal.setProducts("充值钻石");
        requestDatal.setSign(SignUtil.getSign(requestDatal.toMap()));
        try {
            requestDatal.setProducts(URLEncoder.encode("充值钻石","utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        view.addObject("order",requestDatal);
        return view;
    }

    /**
     * 查询订单
     * @param search
     * @return
     * @throws ServerException
     */
    @GetMapping("/list")
    @ResponseBody
    public  Object findOrderList(PayOrderSearch search) throws ServerException {
        return RestResultGenerator.genSuccessResult(payAPI.findPayOrder(search));
    }

    /**
     * 支付回调
     * @param request
     * @param response
     */
    @GetMapping("/payCallback")
    @ResponseBody
    public  Object  payCallback(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> params=new HashedMap();
        params.put("retcode",request.getParameter("retcode"));
        params.put("retmsg",request.getParameter("retmsg"));
        params.put("nonce_str",RandomStringGenerator.getRandomStringByLength(32));
        params.put("nonce_str",request.getParameter("sign"));
        VPayCallbackData callbackData=new VPayCallbackData();
        callbackData.setOut_trade_no(request.getParameter("business_no"));
        callbackData.setTransaction_id(request.getParameter("order_num"));

        if("SUCCESS".equals(request.getParameter("retcode"))){
            callbackData.setResult_code("SUCCESS");

        }else {
            callbackData.setResult_code("FAIL");
            callbackData.setErr_code_des(request.getParameter("retmsg"));
        }
        try {
            payAPI.payCallback(callbackData);
        } catch (ServerException e) {
            params.put("retcode","FAIL");
            params.put("retmsg","订单状态修改失败!");
            log.error("订单状态修改失败!"+e.getMessage());
        }
        return params;
    }

    @GetMapping("/succsesspage")
    public  ModelAndView  paySusscesPage(HttpServletRequest request, HttpServletResponse response){
        ModelAndView view=new ModelAndView("pay/paysuccsess");
        view.addObject("gold",request.getParameter("gold"));
        return view;
    }


    @PostMapping("/payGuard")
    @TokenIntercept(checkVisitor=true)
    @ResponseBody
    public  Object payGuard(String guardMId,Integer guardId)throws ServerException{
        AccessUser accessUser= RequestUtils.getUser();
        guardApi.purchase(accessUser.getUserId(),guardId,guardMId);
        return RestResultGenerator.genSuccessResult();
    }

    /**
     * 兑换钻石
     * @param diamons
     * @return
     */
    @PostMapping("/exchangeDiamons")
    @TokenIntercept(checkVisitor = true)
    @ResponseBody
    public Object ticketExchangeDiamons(Integer diamons)throws ServerException{
        AccessUser accessUser= RequestUtils.getUser();
        payAPI.ticketExchangeDiamons(accessUser.getUserId(),diamons);
        return RestResultGenerator.genSuccessResult();
    }
}
